/**
 * 
 */
package com.dreamsinpost.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import com.dreamsinpost.DreamsInPostActivity;
import com.dreamsinpost.R;
import com.dreamsinpost.custom.ArrayAdapterForCustomList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaRecorder;
import android.net.Uri;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Environment;
import android.text.GetChars;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

/**
 * @author abrysov
 *
 */
public class Main extends Activity implements OnClickListener{

	private static final String TAG = "_dip_Main.class";
	
	private static ArrayList<String> alMusicFilesNames = null;
	
	
	private FrameLayout flGetPhoto = null;
	private FrameLayout flGetMP3 = null;
	private FrameLayout flMIX = null;
	private FrameLayout flForPhoto = null;
	
	private String imageFilePath = null;
	private Uri imageFileURI = null;
	
	private ImageView imv = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainform);
		
		
		
		flForPhoto = (FrameLayout)findViewById(R.id.mainform_fl_photo);
		
		imv = (ImageView) findViewById(R.id.mainform_iv_select_photo);
		imv.setVisibility(View.INVISIBLE);
		
		flGetPhoto = (FrameLayout)findViewById(R.id.mainform_fl_select_photo);
		flGetPhoto.setOnClickListener(this);
		
		flGetMP3 = (FrameLayout)findViewById(R.id.mainform_fl_select_audio);
		flGetMP3.setOnClickListener(this);
		
		flMIX = (FrameLayout)findViewById(R.id.mainform_fl_encode_video);
		flMIX.setOnClickListener(this);
		
	}
	
	private void getPhotoFromCamera() {

		imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()+
				"/tmp/dreampicture.jpg";
		
		File imageFile = new File (imageFilePath);
		imageFileURI = Uri.fromFile(imageFile);
		
		Intent iCamera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		iCamera.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileURI);
		startActivityForResult(iCamera, DreamsInPostActivity.FORM_CAMERA);
		
	}
	
	private void getMP3File() {
		File defaultMusicFolder = null;
		alMusicFilesNames = new ArrayList<String>();
		
		// create dir for music
		try {
			
			defaultMusicFolder = new File ("/mnt/sdcard/Music");//getExternalFilesDir(Environment.DIRECTORY_MUSIC);
			if (!defaultMusicFolder.exists()){
				defaultMusicFolder.mkdir();
			}
			
			Log.i(TAG, "default music folder : " + defaultMusicFolder.getPath());
			

		} catch (Exception e) {
			Log.e(TAG, "err: " + e.getMessage());
		}
		
		for (File e : defaultMusicFolder.listFiles()){
			
			if (e.getPath().contains(".mp3")) {
				
				alMusicFilesNames.add(e.getPath());
			}
			Log.i(TAG, "file in default music folder : " + e.getPath());
		}
		Log.i(TAG, "there are " + alMusicFilesNames.size() + " media files");
		
		
		
		startActivityForResult(new Intent(getApplicationContext(), SelectMediaFile.class),
				DreamsInPostActivity.ACTIVITI_SELECT_MEDIA_FILE);
		
		
	}
	
	public static ArrayList<String> getNamesMediaFiles () {
		return alMusicFilesNames;
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
			
		if (resultCode == RESULT_OK){
			
			Display currentDisplay = getWindowManager().getDefaultDisplay();
			
			int dw = flForPhoto.getWidth();
			int dh = flForPhoto.getHeight();
			
			// Load up the image's dimensions not the image itself
			BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
			bmpFactoryOptions.inJustDecodeBounds = true;
			Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
			
			int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)dh);
			int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)dw);
			
			Log.v("HEIGHTRATIO",""+heightRatio);
			Log.v("WIDTHRATIO",""+widthRatio);
			// If both of the ratios are greater than 1,
			// one of the sides of the image is greater than the screen
			if (heightRatio > 1 && widthRatio > 1){
				if (heightRatio > widthRatio){
					// Height ratio is larger, scale according to it
					bmpFactoryOptions.inSampleSize = heightRatio;
				}else{
					// Width ratio is larger, scale according to it
					bmpFactoryOptions.inSampleSize = widthRatio;
				}
			}
			// Decode it for real
			bmpFactoryOptions.inJustDecodeBounds = false;
			bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
			// Display it if need
			imv.setImageBitmap(bmp);
			
			imv.setVisibility(View.VISIBLE);
			flGetPhoto.setVisibility(View.INVISIBLE);
			
			
		}else{
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.xml.menu, menu);
	    
	    return true;
	}
//	/*
//	 * Subscribe the menu Items.
//	 * And actions from it.
//	 **/
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.menu_b_settings:
	        	
	        	startActivityForResult(new Intent (getApplicationContext(), Settings.class),
	        							DreamsInPostActivity.FORM_MAIN);
	        	break;
	        
	        case R.id.menu_b_info:     
	        	startActivity(new Intent(getApplicationContext(), Info.class));
	        	break;

	    }
	    return true;
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.mainform_fl_select_photo:
			getPhotoFromCamera();
			break;
			
		case R.id.mainform_fl_select_audio:
			getMP3File();
			break;
			
		case R.id.mainform_fl_encode_video:
			
			encodeVideoFile();
			
			break;
			
			

		default:
			break;
		}
		
	}

	private void encodeVideoFile(){
		
		String pathName = Environment.getExternalStorageDirectory().getAbsolutePath()
							+ "/dreams_in_post/dream.mp4";
		
		File fPost = new File ("sdcard/dreams_in_post/");
		if (fPost != null) {
//			fPost.setWritable(true);
				
		}
		
		final MediaRecorder mr = new MediaRecorder();
		mr.setAudioSource(MediaRecorder.AudioSource.VOICE_DOWNLINK);
		mr.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
//		mr.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
		mr.setAudioChannels(1);
		mr.setAudioEncodingBitRate(96);
		mr.setOutputFile(pathName);
		try {
			mr.prepare();
			mr.start();
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		new Thread(){
			
			public void run() {
				
				try {
					sleep(5000);
					mr.stop();
					mr.reset();
					mr.release();
				} catch (Exception e) {
					// TODO: handle exception
				}
				
			};
			
		}.start();
		
	}


}
